package cn.itsource.basic.aop;


import cn.itsource.basic.annotation.Repeat;
import cn.itsource.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//@Aspect 开启切面
//@Component 交给spring容器管理
@Aspect
@Component
@Slf4j
public class RepeatAop {

    @Autowired
    RedisService redisService;

    /**
     * 定义切点
     * @param repeat
     */
    @Pointcut("@annotation(repeat)")
    public void cut(Repeat repeat){

    }

    //    在方法之前执行
    @Before("cut(repeat)")
    public void before(JoinPoint joinPoint, Repeat repeat){
        //RequestContextHolder  从tomcat里面拿到 ServletRequest 拿 HttpServletRequest
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //拿到对应的ip
        String ip = request.getRemoteAddr();
        //拿到对应的url
        String url = request.getRequestURI();
        log.info ("当前用户访问的ip+url:{}{}",ip,url);
        //判断该用户是否重复提交
        if (redisService.hasKey (ip+url)){
            log.info ("该用户正在重复请求");
            throw new RuntimeException ("哥哥,你太快了");
        }
        //获取当前注解上的时间
        int i = repeat.value ();
        redisService.setStringKeyAndValue (ip+url,ip+url,i);


    }
}